package leechapi.main;

import static leechapi.main.Log.log;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.htmlparser.Parser;

public abstract class AbstractLeecher implements Runnable {

	private ProcessingContext pc;
	private String url;
	private String description;

	public AbstractLeecher(String url, String description, ProcessingContext pc) {
		super();
		this.pc = pc;
		this.url = url;
		this.description = description;
	}

	public void run() {
		boolean workToDo = true;
		PreparedStatement insertStatement = null;
		try {
			insertStatement = pc
					.getConnection()
					.prepareStatement(
							"insert into offre (offre,prix,date,url,code_postal,site) values (?,?,?,?,?,?)");
			while (workToDo) {
				ParsableInput input = buildNextParsableInput();
				Parser p = null;
				int nbEssais = 0;
				boolean parseDone = false;
				while (nbEssais <= 3 && !parseDone) {
					try {
						nbEssais++;
						p = input.parse();
						parseDone = true;
					} catch (Exception e) {
						e.printStackTrace();
						Thread.sleep(5000);
					}
				}
				workToDo = extractDataFromParser(p, insertStatement);
			}
		} catch (Exception e) {
			log(Thread.currentThread().getName()
					+ " : Erreur dans le leecher de " + url + " : "
					+ e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				insertStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		log(Thread.currentThread().getName() + " : Leech de " + description
				+ " - FIN");
	}

	protected abstract boolean extractDataFromParser(Parser p,
			PreparedStatement ppInsert) throws Exception;

	protected abstract ParsableInput buildNextParsableInput();

	protected ProcessingContext getPc() {
		return pc;
	}

	protected void setPc(ProcessingContext pc) {
		this.pc = pc;
	}

	protected String getUrl() {
		return url;
	}

	protected void setUrl(String url) {
		this.url = url;
	}

	protected String getDescription() {
		return description;
	}

	protected void setDescription(String description) {
		this.description = description;
	}

}
